<?php
/**
 * 秒杀
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/7
 * Time: 14:44
 */

namespace Admin\Controller;

use Think\Model;

class MiaoshaController extends BaseController
{
    public  $order_status;
    public  $shipping_status;
    public  $pay_status;
    /*
     * 初始化操作
     */
    public function _initialize() {
        parent::_initialize();
        C('TOKEN_ON',false); // 关闭表单令牌验证
        // 订单 支付 发货状态
        $this->order_status = C('ORDER_STATUS');
        $this->pay_status = C('PAY_STATUS');
        $this->shipping_status = C('SHIPPING_STATUS');
        $this->assign('order_status',$this->order_status);
        $this->assign('pay_status',$this->pay_status);
        $this->assign('shipping_status',$this->shipping_status);
    }
    /**
     * 秒杀管理
     */
    public function index()
    {
        //todo 秒杀订单
        $begin = date('Y/m/d',(time()-30*60*60*24));//30天前
        $end = date('Y/m/d',strtotime('+1 days'));
        $this->assign('timegap',$begin.'-'.$end);
        $this->display();
    }

    /**
     * 设置秒杀开放时间
     */
    public function setting_time()
    {
        $open_time = M('miaosha_time')->where(['id' => 1])->getField('open_time');
        $open_time = json_decode($open_time, true);
        if (IS_POST) {
            $open_time = I('post.open_time');
            $open_time = json_encode($open_time, JSON_UNESCAPED_UNICODE);
            $res = M('miaosha_time')->where(['id' => 1])->save(['open_time' => $open_time]);
            if ($res) {
                $this->success("操作成功", U('Miaosha/setting_time'));
                exit;
            } else {
                $this->error("操作失败", U('Miaosha/setting_time'));
                exit;
            }
        }
        $this->assign("open_time", $open_time);
        $this->display();

    }

    /**
     * 秒杀设置
     */
    public function setting_miaosha()
    {
        if (IS_POST) {
            $data = I('post.');
            unset($data['__hash__']);
            // if ($data['unpaid'] < 0) {
            //     $this->success("请设置正确时间", U('Miaosha/setting_miaosha'));
            //     exit;
            // }
            $res = M('ms_setting')->where(['id' => 1])->save($data);
            if ($res) {
                $this->success("操作成功", U('Miaosha/setting_miaosha'));
                // $this->del_order_while();
                exit;
            } else {
                $this->error("操作失败", U('Miaosha/setting_miaosha'));
                exit;
            }
        }
        $setting = M('ms_setting')->find(1);
        $this->assign('setting', $setting);
        $this->display();
    }

    //秒杀开启后循环删除超时订单
    public function del_order_while(){
        ignore_user_abort(true);
        set_time_limit(0);
        date_default_timezone_set("PRC");
        ini_set('memory_limit','512M');
        $test = M('test');
        $set = M('ms_setting');
        do{

            $bj = $set->find(STORE_ID);
            if($bj['miaosha'] == 0){
                break;
            }
            // file_put_contents('./config.php',date('Y-n-j G:i:s'));
            $this->close_order();
            // $test->add(array('an'=>date('Y-m-d H:i:s')));
            sleep(5);
            
        }while(true);
    }

    //秒杀任务删除订单
    public function close_order(){
        $time = M('ms_setting')->where(array('store_id'=>STORE_ID))->find();
        if(!$time['unpaid']){
            $time = time() - 60;
        }else{
            $time = time() - $time['unpaid']*60;
        }
        $order = M('order')->field('order_id,user_id')->where(array('pay_status'=>0,'order_status'=>0,'is_ms'=>1))->where('add_time <='.$time)->select();
        if(!$order){
            return ;
        }
        $ids = '';
        $data = array();
        $time = time();
        foreach ($order as $k => $v) {
            $ids .= $v['order_id'].',';
            $data[] = array(
                'order_id' => $v['order_id'],
                'action_user' => $v['user_id'],
                'action_note' => '系统自动取消订单',
                'order_status' => 3,
                'log_time' => $time,
                'status_desc' => '秒杀超时,取消订单',
                );
        }
        $ids = trim($ids,',');
        M('order')->where("order_id in(".$ids.")")->save(array('order_status'=>3));
        M('order_action')->addAll($data);//订单操作记录
    }

    /**
     * 秒杀商品列表
     */
    public function ms_goodslist()
    {
        //todo 查询参加秒杀的商品
        $list = M('miaosha_goods')->group('goods_id')->select();
		
        foreach ($list as $k => $v) {
			
            $list[$k]['attr'] = json_decode($list[$k]['attr'], true);
			$list[$k]['store_name']= M('store')->where(array('store_id'=>$v['store_id']))->getField("store_name");
        }
        $this->assign('list', $list);
        $this->display();
    }


    /**
     * 添加秒杀商品
     */
    public function add_msgoods()
    {
        if (IS_POST) {
            $g = M('goods');
            $data = $_POST;
            $ddd = array();
            foreach($data['goods_id'] as $k => $v){
                $good = $g->where(array('goods_id'=>$v))->find();
                $goods = json_encode($good, JSON_UNESCAPED_UNICODE);
                if(!$goods){
                    continue;
                }
                for($i = strtotime($data['start_time']);$i<= strtotime($data['end_time']);$i+=86400){
                    $ymd = date('Y-m-d',$i);
                    foreach($data['open_time'] as $hours){
                        $ddd[] = array(
                            'store_id'      => STORE_ID,
                            'goods_id'      => $v,
                            'start_time'    => $hours,
                            'open_time'     => $ymd,
                            'buy_max'       => $data['buy_max'],
                            'attr'           => $goods,
                            );
                    }
                }
            }
            $res = M('miaosha_goods')->addAll($ddd);
            if(!$res){
                $this->error("添加失败");
            }
            $this->success("添加商品成功", U('Miaosha/ms_goodslist'));
            exit;
        }
        $info['start_time'] = date('Y-m-d');
        $info['end_time'] = date('Y-m-d', time() + 3600 * 30 * 24);
        $level = M('user_level')->select();
        $this->assign('level', $level);
        $this->assign('min_date', date('Y-m-d'));
        $this->assign('info', $info);
        $this->display();
    }

    /**
     * 删除秒杀商品
     * del_ms_goods/id/5
     */
    public function del_ms_goods()
    {
        $goods_id = $_GET['goods_id'];
        $res = M('miaosha_goods')->where(['goods_id'=>$goods_id])->delete();
        if($res){
            $this->ajaxReturn(['status' => 1, 'msg' => '删除成功']);
        }
        else{
            $this->ajaxReturn(['status' => 0, 'msg' => '删除失败']);
        }
    }

    /**
     * 设置秒杀商品价格
     */
    public function ajax_goodsprice()
    {
        $data = I('post.');
         /**
          * todo save() 有待解决
          */
        $data['ms_price'] = (float)$data['ms_price'];
        $a = gettype($data['ms_price']);
        $res = M('miaosha_goods')->where(['goods_id' => $data['goods_id']])->save(['ms_price'=>$data['ms_price']]);
        if ($res) {
            $this->ajaxReturn(['status' => 1, 'msg' => '设置成功', "data" => $data]);
        } else {
            $this->ajaxReturn(['status' => 0, 'msg' => '设置失败', 'type'=>$a]);
        }

    }

    /**
     * 设置秒杀商品数量
     */
    public function ajax_goodsnum()
    {
        $data = I('post.');
        /**
         * todo save() 有待解决
         */
        $data['ms_num'] = (int)$data['ms_num'];
        $a = gettype($data['ms_num']);
        $res = M('miaosha_goods')->where(['goods_id' => $data['goods_id']])->save(['ms_num'=>$data['ms_num']]);
        if ($res) {
            $this->ajaxReturn(['status' => 1, 'msg' => '设置成功']);
        } else {
            $this->ajaxReturn(['status' => 0, 'msg' => '设置失败','type'=>$a]);
        }
    }

    /**
     * 秒杀订单接收搜索条件
     */
    public function export_order()
    {
        //搜索条件
        $where = "where store_id =" . STORE_ID . " ";
        $consignee = I('consignee');
        if ($consignee) {
            $where .= " AND consignee like '%$consignee%' ";
        }
        $order_sn = I('order_sn');
        if ($order_sn) {
            $where .= " AND order_sn = '$order_sn' ";
        }
        if (I('order_status')) {
            $where .= " AND order_status = " . I('order_status');
        }

        $timegap = I('timegap');
        if ($timegap) {
            $gap = explode('-', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
            $where .= " AND add_time>$begin and add_time<$end";
        }
        $region = M('region')->getField('id,name');

        $sql = "select *,FROM_UNIXTIME(add_time,'%Y-%m-%d') as create_time from __PREFIX__order $where order by order_id";
        $orderList = D()->query($sql);
        $strTable = '<table width="500" border="1">';
        $strTable .= '<tr>';
        $strTable .= '<td style="text-align:center;font-size:12px;width:120px;">订单编号</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="100">日期</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">收货人</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">收货地址</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">电话</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">订单金额</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">实际支付</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">支付方式</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">支付状态</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">发货状态</td>';
        $strTable .= '<td style="text-align:center;font-size:12px;" width="*">商品信息</td>';
        $strTable .= '</tr>';

        foreach ($orderList as $k => $val) {
            $strTable .= '<tr>';
            $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;' . $val['order_sn'] . '</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['create_time'] . ' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">' . "{$region[$val['province']]},{$region[$val['city']]},{$region[$val['district']]},{$region[$val['twon']]}{$val['consignee']}" . ' </td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['address'] . '</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['mobile'] . '</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['goods_price'] . '</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['order_amount'] . '</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">' . $val['pay_name'] . '</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">' . $this->pay_status[$val['pay_status']] . '</td>';
            $strTable .= '<td style="text-align:left;font-size:12px;">' . $this->shipping_status[$val['shipping_status']] . '</td>';
            $orderGoods = D('order_goods')->where('order_id=' . $val['order_id'])->select();
            $strGoods = "";
            foreach ($orderGoods as $goods) {
                $strGoods .= "商品编号：" . $goods['goods_sn'] . " 商品名称：" . $goods['goods_name'];
                if ($goods['spec_key_name'] != '') $strGoods .= " 规格：" . $goods['spec_key_name'];
                $strGoods .= "<br />";
            }
            unset($orderGoods);
            $strTable .= '<td style="text-align:left;font-size:12px;">' . $strGoods . ' </td>';
            $strTable .= '</tr>';
        }
        $strTable .= '</table>';
        unset($orderList);
        downloadExcel($strTable, 'order');
        exit();
    }

    public function info_miaosha_goods(){
        // echo '<pre>';
        // var_dump($_GET);
        // echo '</pre>';
        $miaosha_goods = M('miaosha_goods');
        $ms = $miaosha_goods->where(['goods_id'=>$_GET['goods_id']])->select();
        $last_time = $_GET['first_time'] ? $_GET['first_time'] : $ms[0]['open_time'];
        $first_time = $_GET['last_time'] ? $_GET['last_time'] : $ms[count($ms)-1]['open_time'];
        $mss = $miaosha_goods->where(['goods_id'=>$_GET['goods_id']])->where("open_time between '".$first_time."' and '".$last_time."'")->select();
        foreach($ms as $k=>$v){
            $ms[$k]['attr'] = json_decode($ms[$k]['attr'], true);
        }
        $this->assign('gggg',M('goods')->find($_GET['goods_id']));
        $this->assign('first_time',$first_time);
        $this->assign('last_time',$last_time);
        $this->assign('ms_goods',$mss);
        $this->display();
    }

    /**
     * 删除秒杀商品
     * del_ms_goods/id/5
     */
    public function del_ms_goods_one()
    {
        $id = $_GET['id'];
        $res = M('miaosha_goods')->where(['id'=>$id])->delete();
        if($res){
            $this->ajaxReturn(['status' => 1, 'msg' => '删除成功']);
        }
        else{
            $this->ajaxReturn(['status' => 0, 'msg' => '删除失败']);
        }
    }

    /**
     * 设置秒杀商品价格
     */
    public function ajax_goodsprice_one()
    {
        $data = I('post.');
         /**
          * todo save() 有待解决
          */
        $data['ms_price'] = (float)$data['ms_price'];
        $a = gettype($data['ms_price']);
        $res = M('miaosha_goods')->where(['id' => $data['id']])->save(['ms_price'=>$data['ms_price']]);
        if ($res) {
            $this->ajaxReturn(['status' => 1, 'msg' => '设置成功', "data" => $data]);
        } else {
            $this->ajaxReturn(['status' => 0, 'msg' => '设置失败', 'type'=>$a]);
        }

    }

    /**
     * 设置秒杀商品数量
     */
    public function ajax_goodsnum_one()
    {
        $data = I('post.');
        /**
         * todo save() 有待解决
         */
        
        $ms_num= $data['ms_num'];
        $a = gettype($ms_num);
        $res = M('miaosha_goods')->where(['id' => $data['id']])->save(['ms_num' =>$ms_num]);
        if ($res) {
            $this->ajaxReturn(['status' => 1, 'msg' => '设置成功']);
        } else {
            $this->ajaxReturn(['status' => 0, 'msg' => '设置失败','type'=>$a]);
        }
    }
}